package 课程设计报告_hb_6_30;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.junit.Test;

import 课程设计报告_hb_7_1.Transaction;

/**
 * map找数据比arraylist、set、数组快
 * @author Jiang Zhiyan
 *
 * 2021年6月30日 下午3:53:21
 *
 */
public class TestTrader {

	public List<Transaction> initData() {
		Trader raoul = new Trader("Raoul", "Cambridge");
		Trader mario = new Trader("Mario", "Milan");
		Trader alan = new Trader("Alan", "Cambridge");
		Trader brian = new Trader("Brian", "Cambridge");
		List<Transaction> transactions = Arrays.asList(new Transaction(brian, 2011, 300),
				new Transaction(raoul, 2012, 1000), new Transaction(raoul, 2011, 400),
				new Transaction(mario, 2012, 710), new Transaction(mario, 2012, 700), new Transaction(alan, 2012, 950));
	   return transactions;
	}

	// 对一个交易列表按货币分组，获得该货币的所有交易额总和
	// 对交易的城市进行分组，获得交易的相关信息
		public Map<String, List<Transaction>> locationTransaction(List<Transaction> datas) {
			Map<String,List<Transaction>> map= new HashMap<>();
			for(Transaction transaction : datas) {
//				1、获得交易货币的名称
				String city = transaction.getTrader().getCity();
//				2、判断name是否在map中存在
				if(map.containsKey(city)) {
//					1、获得相应的list
					List<Transaction> list = map.get(city);
					list.add(transaction);
				}else {
					List<Transaction> list = new ArrayList<Transaction>();
					list.add(transaction);
					map.put(city, list);
				}
			}
			return map;

		}

		// 获得每个城市的总交易额
		public Map<String, Integer> locationCounter(Map<String, List<Transaction>> datas) {
			Map<String ,Integer> map= new HashMap<>();
			for(String  key :datas.keySet()) {
				List<Transaction> list = datas.get(key);
				int sum=0;
				for(Transaction t:list) {
					sum+=t.getValue();
				}
				map.put(key, sum);
			}
			return map;
		}
		
		@Test
		public void test() {
			List<Transaction> datas=initData();
			Map<String ,List<Transaction>> maps = locationTransaction(datas);
			Map<String ,Integer> counterMap = locationCounter(maps);
			System.out.println(counterMap);
		}


}
